import 'package:boss/common/common.dart';
import 'package:boss/models/login_user.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:flustars/flustars.dart' as flustars;

part 'cache_user.g.dart';

@JsonSerializable(explicitToJson: true)
class CacheUser {
  LoginUser loginUser;
  DateTime loginTime;

  CacheUser({this.loginUser, this.loginTime});

  factory CacheUser.fromJson(Map<String, dynamic> srcJson) => _$CacheUserFromJson(srcJson);

  Map<String, dynamic> toJson() => _$CacheUserToJson(this);

  //是否已经过期
  bool get isExpired => (loginTime?.add(Duration(days: 120))?.isBefore(DateTime.now()) ?? true)||loginUser.isExpired;

  //存储用户
  static Future<bool> cacheUser(CacheUser cacheUser) {
    return flustars.SpUtil.putObject(Constant.spLoginData, cacheUser);
  }

  //清空用户
  static Future<bool> clearCacheUser() {
    return flustars.SpUtil.remove(Constant.spLoginData);
  }

  //读取用户
  static CacheUser getCacheUser() {
    return flustars.SpUtil.getObj<CacheUser>(Constant.spLoginData, (json) => CacheUser.fromJson(json), defValue: null);
  }



  //是否已存在用户并切没有过期
  static CacheUser get usableUser {
    var user = getCacheUser();

    if (user == null || user.isExpired) {
      return null;
    }

    return user;
  }
}